//
//  ZPTabBar.swift
//  weibo
//
//  Created by zhangpeng on 16/4/16.
//  Copyright © 2016年 zhangpeng. All rights reserved.
//

import UIKit

protocol ZPTabBarDelegate:NSObjectProtocol{

    func composeButtonClick()
}

class ZPTabBar: UITabBar {


     // 声明一个代理 (声明一个代理需要用weak 修饰 方法循环引用  使用weak 修饰以后 必须 继承基协议 NSObjectProtocol)
    
    weak var zpDelegate:ZPTabBarDelegate?
    
   override init(frame: CGRect) {
        super.init(frame: frame)

    setupUI()
    
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }

    //MARK : - 设置控件
    func setupUI(){
    
        addSubview(composeButton)
    }
    
    //MARK : - 对子控件布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // UITabBarButton 宽度
        let width = SCREENW / 5
        //使用标示
        var index: CGFloat = 0
        
        for value in self.subviews{
        
             // 先判断他的子控件知否是我们的需要的UITabBarButton
            if value .isKindOfClass(NSClassFromString("UITabBarButton")!){
            
                value.frame.origin.x = index * width
                value.frame.size.width = width

                index++
                
                if index == 2{
                
                    index++
                }
            }
  
        }
        composeButton.center.x = self.frame.width * 0.5
        composeButton.center.y = self.frame.height * 0.5
        
    }
    
    //懒加载中间的加号按钮
    //private 定义为私有的
   private lazy var composeButton:UIButton = {
        let button = UIButton()
    //添加点击事件
    button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
    
    //设置背景图片
    button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
    button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
    
    //设置按钮图片
    button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
    button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
    
    button.sizeToFit()
        
    
    return button
        }()
        // MARK: -监听编辑按钮的点击事件
    //监听编辑按钮的点击事件
  @objc private func composeButtonClick(){
    
        zpDelegate?.composeButtonClick()
    }
    
}
